package com.sx.manage.service.company.send;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.sx.cache.Cache;
import com.sx.common.util.SquenceUtil;
import com.sx.common.util.http.model.PrimarykeyClass;
import com.sx.common.util.message.MessageType;
import com.sx.common.vo.BaseVO;
import com.sx.manage.exception.MAjaxErrorRollbackException;
import com.sx.manage.service.company.IMCompanyInfoCollectSendRecordService;
import com.sx.manage.service.sys.IMBaseSystemConfigInfoService;
import com.sx.manage.util.WebServiceUtil;
import com.sx.model.constants.MSystemConstants;
import com.sx.model.constants.type.company.MSendStatusType;
import com.sx.model.manage.mybatis.form.company.MCompanyInfoCollectSendRecordForm;
import com.sx.model.manage.mybatis.form.sys.MSystemConfigInfoForm;
import com.sx.model.manage.mybatis.vo.company.MCompanyInfoCollectSendRecordVO;
import com.sx.model.manage.mybatis.vo.consumer.login.MConsumerLoginVO;
import com.sx.model.manage.mybatis.vo.result.ResultBooleanVO;
import com.sx.model.manage.mybatis.vo.result.ResultListVO;
import com.sx.model.manage.mybatis.vo.result.ResultObjectVO;
import com.sx.model.manage.mybatis.vo.sys.MSysConfigVO;
import com.trusdom.commons.Cryptos;

/**
 * 公司信息录入url发送记录
 *
 * @author Administrator
 * @version 1.0.0 Wed Jul 26 00:00:00 CST 2017
 */
@Service("comCollectSendRecordWebService")
@SuppressWarnings("rawtypes")
public class MComCollectSendRecordWebService {
	/*** 日志 */
	private Logger _log = LoggerFactory.getLogger(this.getClass());
    @Resource(name="redisCache") 	
	protected Cache cache; 
    //公司信息收集
	@Resource(name = "companyInfoCollectSendRecordServiceImpl")
	private IMCompanyInfoCollectSendRecordService companyInfoCollectSendRecordServiceImpl;

	//系统参数配置
	@Resource(name="mBaseSystemConfigInfoServiceImpl")
	private IMBaseSystemConfigInfoService mBaseSystemConfigInfoServiceImpl;

	public Logger get_log() {
		return _log;
	}

	public void set_log(Logger _log) {
		this._log = _log;
	}

	public IMBaseSystemConfigInfoService getmBaseSystemConfigInfoServiceImpl() {
		return mBaseSystemConfigInfoServiceImpl;
	}

	public void setmBaseSystemConfigInfoServiceImpl(IMBaseSystemConfigInfoService mBaseSystemConfigInfoServiceImpl) {
		this.mBaseSystemConfigInfoServiceImpl = mBaseSystemConfigInfoServiceImpl;
	}

	public Cache getCache() {
		return cache;
	}

	public void setCache(Cache cache) {
		this.cache = cache;
	}

	public IMCompanyInfoCollectSendRecordService getCompanyInfoCollectSendRecordServiceImpl() {
		return this.companyInfoCollectSendRecordServiceImpl;
	}

	public void setCompanyInfoCollectSendRecordServiceImpl(
			IMCompanyInfoCollectSendRecordService companyInfoCollectSendRecordServiceImpl) {
		this.companyInfoCollectSendRecordServiceImpl = companyInfoCollectSendRecordServiceImpl;
	}

	/**增加数据*/
	public ResultBooleanVO save(MCompanyInfoCollectSendRecordForm form,
			MConsumerLoginVO loginConsumer){
		
		_log.debug("获取数据库配置的email地址");
		ResultObjectVO<String> send_urlResult  = this.send_url();
		if( !send_urlResult.isSuccess()){
			return new ResultBooleanVO(false,null,send_urlResult.getMsg());
		}
		
		Long company_id = Long.valueOf(SquenceUtil.makePrimarykey(PrimarykeyClass.SX_UNIFY_CONSUMER,"", cache) );
		
		String send_url = send_urlResult.getObjVo()+"?company_id="+Cryptos.encode(String.valueOf(company_id));
		form.setSend_url(send_url);
		

		_log.debug("发送邮件");
		BaseVO<?>  baseVO = this.send_Email( form.getEmail(), send_url, company_id);
		if( !baseVO.isSuccess()){			
			form.setSend_status( MSendStatusType.SEND_FAIL);
		}else{
			form.setSend_status( MSendStatusType.SEND_SUCCESS);
			form.setSend_date(new Date());
		}
		
		_log.debug("保存邮件信息");
		ResultBooleanVO saveResultVO = companyInfoCollectSendRecordServiceImpl.save(form, loginConsumer);
		if( !saveResultVO.isSuccess()){
			_log.error("错误提示："+saveResultVO.getMsg());
			if(!baseVO.isSuccess()){
				return new ResultBooleanVO(false,null,"邮件发送失败，信息保存失败，请重新发送。");
			}
			return saveResultVO;
		}else{
			if(!baseVO.isSuccess()){
				return new ResultBooleanVO(false,null,"邮件发送失败，信息已经保存，可以在发送记录中点击'重新发送'按钮");
			}
		}		
		return new ResultBooleanVO();
	}
	/**重新发送*/
	public ResultBooleanVO again(Long id,
			MConsumerLoginVO loginConsumer){
		
		_log.debug("获取发送记录数据");
		ResultObjectVO<MCompanyInfoCollectSendRecordVO> result  = this.companyInfoCollectSendRecordServiceImpl.queryById(id);
		if( !result.isSuccess()){
			return new ResultBooleanVO(false,null,result.getMsg());
		}
		if( null == result.getObjVo()){
			return new ResultBooleanVO(false,null,"数据不存在");
		}
	
		String send_url =  result.getObjVo().getSend_url();
		String company_id_str = send_url.substring( send_url.indexOf("company_id=")+11);
		Long company_id = Long.valueOf( Cryptos.decode(company_id_str));
		_log.debug("发送邮件");
		BaseVO<?>  baseVO = this.send_Email( result.getObjVo().getEmail(),send_url, company_id);
		
		MCompanyInfoCollectSendRecordForm form = new MCompanyInfoCollectSendRecordForm();
		if( !baseVO.isSuccess()){			
			return new  ResultBooleanVO(false,null,"发送失败");
		}else{
			form.setSend_status( MSendStatusType.SEND_SUCCESS);
			form.setSend_date(new Date());
			form.setId( result.getObjVo().getId());
		}		
		
		_log.debug("更新发送记录信息");
		ResultBooleanVO saveResultVO = companyInfoCollectSendRecordServiceImpl.update(form, loginConsumer);
		_log.debug("错误提示："+saveResultVO.getMsg());						
	
		return new ResultBooleanVO();
	}
	/**增加数据*/
	public ResultBooleanVO send_again(MCompanyInfoCollectSendRecordForm form,MConsumerLoginVO loginConsumer){
		
		_log.debug("获取发送信息loginConsumer={}",loginConsumer);
		ResultObjectVO<MCompanyInfoCollectSendRecordVO> objResult =companyInfoCollectSendRecordServiceImpl.queryById( form.getId());
		if( !objResult.isSuccess()){
			_log.error("获取数据出错："+objResult.getMsg());
			return new ResultBooleanVO(false,null,objResult.getMsg());
		}
		String send_url = objResult.getObjVo().getSend_url();
		String company_id_str = send_url.substring(send_url.indexOf("company_id="));
		_log.debug("发送邮件");
		BaseVO<?>  baseVO = this.send_Email( form.getEmail(), objResult.getObjVo().getSend_url(),Long.valueOf(company_id_str) );
		if( !baseVO.isSuccess()){
			throw new MAjaxErrorRollbackException( baseVO.getMsg() );//返回到配置文件中定义的路径
		}
		return new ResultBooleanVO();
	}
	
	/**
	 * 激活 发送邮件
	 * @param userIds
	 */
	private BaseVO<?> send_Email(String email,String sen_url,Long userId){
		if (null == email) {
			return  new BaseVO(false,null,"email地址不能为空");
		}
		if (null == sen_url) {
			return   new BaseVO(false,null,"用户录入公司信息链接不能为空");
		}
		_log.info("公司信息收集:===发送邮件名称:"+email);
		List<String> list = new ArrayList<>();
		list.add(email);
	
		String text = MSystemConstants.COMPANY_INFL_COLLECT;
		text = WebServiceUtil.formatValues(text,null,null,sen_url);
		MSysConfigVO vo = mBaseSystemConfigInfoServiceImpl.queryByIdSystemConfig(new MSystemConfigInfoForm(MSystemConstants.MESSAGE_HOST_URL)).getObjVo();
		if (null == vo) {
			_log.info("用户激活:===发送邮件参数错误，请联系管理员配置"+MSystemConstants.MESSAGE_HOST_URL+"该参数！");
			return BaseVO.createSuccessMsg("短信发送参数未配置");
		}
		_log.debug("邮件==用户激活url："+sen_url);
		//发送短信
		return WebServiceUtil.sendTplEmail(null,email, "主题", text, userId.toString(), vo.getConfig_value(), MessageType.EMAIL);
	}
	
	/** 查询发送email 的配置地址**/
	private ResultObjectVO<String> send_url(){
		
		MSystemConfigInfoForm form = new MSystemConfigInfoForm();
        form.setConfig_name( MSystemConstants.COMPANY_COLLECT_EMAIL_URL );
        
        MSysConfigVO sysConfigVO = mBaseSystemConfigInfoServiceImpl.queryByIdSystemConfig(form).getObjVo();
		if (null == sysConfigVO) {
			_log.error("系统没有配置email发送地址");
			return new ResultObjectVO<>(false,null,"系统没有配置email发送地址");
		}				
		ResultObjectVO<String> result=new ResultObjectVO<>();
							   result.setObjVo( sysConfigVO.getConfig_value() );
		return result;
	}

	/**查询分页*/
	public ResultListVO<MCompanyInfoCollectSendRecordVO> queryPage(
			MCompanyInfoCollectSendRecordForm form){
		return companyInfoCollectSendRecordServiceImpl.queryPage(form);
	}

} // end class